<?php
namespace app\api\controller;
use app\model\GoodsModel;
use app\model\ImGroupUserModel;
use app\model\OrderModel;
use app\model\UserModel;
use support\Log;
use support\Request;
use think\facade\Db;
use tool\User;
use \WeChatPay\Builder;
use \WeChatPay\Crypto\Rsa;
use \WeChatPay\Util\PemUtil;
use \WeChatPay\Formatter;

class GoodsController extends Base
{

    public function getOrderList(Request $request){
        $page=$request->post('page',1);
        $user=User::findMe();
        $list=OrderModel::alias('o')
            ->leftJoin('goods g','g.id=o.goods_id')
        ->where('o.user_id',$user['id'])->where('o.pay_status',1)->page($page,10)
            ->field('o.*,g.goods_name,g.goods_img')
            ->select()->toArray();
        s($list);
    }
    public function getGoodsList(Request $request){
        $page=$request->post('page',1);
        $list=GoodsModel::page($page,10)->select()->toArray();
        s($list);
    }
    public function getGoodsOne(Request $request){
        $id=$request->post('id',0);
        $data=GoodsModel::where('id',$id)->find();
        s($data);
    }
    public function tuikuanLinshi(Request $request)
    {
        //生成订单
        $orderNo =$request->post('orderNo', '');
        $money=$request->post('money', 0);
        $out_refund_no=uniqid();

        $wx_xcx_notify_url='https://lizhicang.cn/api/notify/wx2';
        $merchantId = config('wx.pay_mchid');
        // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
        $merchantPrivateKeyFilePath = file_get_contents( base_path().'/zhengshu/wx/apiclient_key.pem');
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
        // 「商户API证书」的「证书序列号」
        $merchantCertificateSerial = config('wx.pay_zhengshu');
        // 从本地文件中加载「微信支付平台证书」，用来验证微信支付应答的签名
        $platformCertificateFilePath = file_get_contents(base_path().'/zhengshu/wx/wechatpay.pem');
        $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
        // 从「微信支付平台证书」中获取「证书序列号」
        $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid'      => $merchantId,
            'serial'     => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs'      => [
                $platformCertificateSerial => $platformPublicKeyInstance,
            ],
        ]);
        try {
            $resp = $instance
                ->chain('/v3/refund/domestic/refunds')
                ->post(['json' => [
                    "out_trade_no"=> $orderNo,
                    "notify_url"=> $wx_xcx_notify_url,
                    "amount"=> [
                        "refund"=> $money*100,//退款金额
                        "total" => $money*100,//支付金额
                        "currency" => "CNY"
                    ],
                    'out_refund_no'=>$out_refund_no
                ]]);
            $t=0;
            if ($resp->getStatusCode()==200) {
                $t=1;

            }
        } catch (\Exception $e) {
            //return ['code' => 0, 'message' => '微信支付错误'];
            // 进行错误处理
            echo $e->getMessage(), PHP_EOL;
            if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
                $r = $e->getResponse();
                echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
                echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
            }
            echo $e->getTraceAsString(), PHP_EOL;
            $params='';
            $t=0;
        }
        if($t){
            s();
        }else{
            e('退款失败');
        }
    }
    //支付
    public function updatePayOrder(Request $request){
        $user=User::findMe();
        $goodsId=$request->post('goodsId',0);

        $wx_xcx_notify_url='https://lizhicang.cn/api/notify/wx';

        $goods=Db::name('goods')->where('id',$goodsId)->find();

        $zong=$goods['money'];
        $ji=$goods['id'].time().\mt_rand(1111,9999).$user['id'];
        $info=[
            'out_trade_no'=>'zong_'.$ji,
            'user_id'=>$user['id'],
            'payment'=>3, //五种支付方式
            'goods_price_zong'=>$zong,
            'goods_id'=>$goods['id'],
            'goods_price'=>$goods['money'],
            'order_num'=>1,
            'phone'=>$user['phone'],
            'postage'=>$goods['postage'],
        ];


        $order=new OrderModel();
        $wo=$order->save($info);
        $order_id=$order->id;
        if($wo){
            $merchantId = config('wx.pay_mchid');
            // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
            $merchantPrivateKeyFilePath = file_get_contents(base_path().'/zhengshu/wx/apiclient_key.pem');
            $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
            // 「商户API证书」的「证书序列号」
            $merchantCertificateSerial = config('wx.pay_zhengshu');
            // 从本地文件中加载「微信支付平台证书」，用来验证微信支付应答的签名
            $platformCertificateFilePath = file_get_contents(base_path().'/zhengshu/wx/wechatpay.pem');
            $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
            // 从「微信支付平台证书」中获取「证书序列号」
            $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
            // 构造一个 APIv3 客户端实例
            $instance = Builder::factory([
                'mchid'      => $merchantId,
                'serial'     => $merchantCertificateSerial,
                'privateKey' => $merchantPrivateKeyInstance,
                'certs'      => [
                    $platformCertificateSerial => $platformPublicKeyInstance,
                ],
            ]);
            try {
                $resp = $instance
                    ->chain('v3/pay/transactions/jsapi')
                    ->post(['json' => [
                        'mchid'        => config('wx.pay_mchid'),
                        "out_trade_no"=> $ji,
                        "appid"=> config('wx.xcx_appid'),
                        "description"=> "向商城付款",
                        "notify_url"=> $wx_xcx_notify_url,
                        "amount"=> [
                            "total"=> (int)($zong*100),
                            //"total"=>1,
                            "currency"=> "CNY"
                        ],
                        "payer"=> [
                            "openid"=> $user['openid_wx']
                        ]
                    ]]);
                if( $resp->getStatusCode()==200){
                    $wo=json_decode($resp->getBody(),true); //prepay_id
                    $params = [
                        'appId'     => config('wx.xcx_appid'),
                        'timeStamp' => (string)Formatter::timestamp(),
                        'nonceStr'  => Formatter::nonce(),
                        'package'   => 'prepay_id='.$wo["prepay_id"],
                    ];
                    $params += ['paySign' => Rsa::sign(
                        Formatter::joinedByLineFeed(...array_values($params)),
                        $merchantPrivateKeyInstance
                    ), 'signType' => 'RSA'];

                    // Db::name('user_gu')->where('id')
                    //   echo json_encode($params);
                    return json([
                        'data'=>$params,
                        'code'=>200
                    ]);
                    // s($params);
                }
            } catch (\Exception $e) {
                //  return ['code' => 0, 'message' => '微信支付错误'];
                // 进行错误处理
                echo $e->getMessage(), PHP_EOL;
                if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
                    $r = $e->getResponse();
                    echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
                    echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
                }
                echo $e->getTraceAsString(), PHP_EOL;
            }
        }else{
            e('插入数据库失败');
        }

    }
}
